package org.xbzheng.restful_study.tool;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

/**
 * Created by Administrator on 2016/10/28.
 */
public class JsonTool {
    private static final Logger LOG = LoggerFactory.getLogger(JsonTool.class);

    public static String toJson(Object obj){
        if(ObjectUtils.isEmpty(obj)) return "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOG.error("Convert object to json string failed:", e);
            return "";
        }
    }

    public static <T> T toObject(String json, Class clz){
        if(StringUtils.isBlank(json)) return null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            return (T)mapper.readValue(json, clz);
        } catch (IOException e) {
            LOG.error("Convert json string to Object failed:", e);
            return null;
        }
    }
}
